const mysql = require('mysql2/promise');
const axios = require('axios');

// 数据库配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: '123456', // 请根据实际情况修改
  database: 'chatime',
  port: 3306
};

const API_BASE = 'http://10.133.25.98:3000/api'; // 使用实际WLAN IP
const userA = 'user1'; // 关注者
const userB = 'user2'; // 被关注者

async function main() {
  const pool = mysql.createPool(dbConfig);
  try {
    // 1. 清理历史数据
    await pool.execute("DELETE FROM follows WHERE (user_id=? AND follow_id=?) OR (user_id=? AND follow_id=?)", [userA, userB, userB, userA]);
    await pool.execute("DELETE FROM friends WHERE (user_id=? AND friend_id=?) OR (user_id=? AND friend_id=?)", [userA, userB, userB, userA]);
    console.log('✅ 已清理历史关注和好友数据');

    // 2. userA 关注 userB
    let resp;
    try {
      resp = await axios.post(`${API_BASE}/follow`, { userId: userA, targetUserId: userB });
      console.log('userA 关注 userB:', resp.data);
      if (!resp.data.success) throw new Error('关注失败: ' + resp.data.message);
    } catch (e) {
      console.error('userA 关注 userB 请求异常:', e.message, e.response?.data, e);
      throw e;
    }

    // 3. userB 关注 userA（互关，自动成为好友）
    try {
      resp = await axios.post(`${API_BASE}/follow`, { userId: userB, targetUserId: userA });
      console.log('userB 关注 userA:', resp.data);
      if (!resp.data.success && resp.data.message !== '已关注') throw new Error('互关失败: ' + resp.data.message);
    } catch (e) {
      console.error('userB 关注 userA 请求异常:', e.message, e.response?.data, e);
      throw e;
    }

    // 4. 检查数据库是否已成为好友
    try {
      const [friends] = await pool.execute(
        'SELECT * FROM friends WHERE (user_id=? AND friend_id=?) OR (user_id=? AND friend_id=?)',
        [userA, userB, userB, userA]
      );
      if (friends.length === 2) {
        console.log('✅ 互相关注后已自动成为好友');
      } else {
        throw new Error('❌ 互关后未自动成为好友');
      }
    } catch (e) {
      console.error('数据库好友关系检查异常:', e.message, e);
      throw e;
    }

    // 5. 检查API好友列表
    try {
      const apiList = await axios.get(`${API_BASE}/friend/list/${userA}`);
      const isFriend = apiList.data.data.some(f => f.friend_id === userB);
      if (isFriend) {
        console.log('✅ API返回userA的好友列表包含userB');
      } else {
        throw new Error('❌ API未返回userB为userA的好友');
      }
    } catch (e) {
      console.error('API好友列表检查异常:', e.message, e.response?.data, e);
      throw e;
    }

    // 6. 取消关注并检查好友关系解除
    try {
      resp = await axios.post(`${API_BASE}/unfollow`, { userId: userA, targetUserId: userB });
      console.log('userA 取消关注 userB:', resp.data);
      if (!resp.data.success) throw new Error('取消关注失败: ' + resp.data.message);
      // 检查数据库
      const [friendsAfter] = await pool.execute(
        'SELECT * FROM friends WHERE (user_id=? AND friend_id=?) OR (user_id=? AND friend_id=?)',
        [userA, userB, userB, userA]
      );
      if (friendsAfter.length === 0) {
        console.log('✅ 取消互关后好友关系已解除');
      } else {
        throw new Error('❌ 取消互关后好友关系未解除');
      }
    } catch (e) {
      console.error('取消关注或好友关系检查异常:', e.message, e.response?.data, e);
      throw e;
    }

    console.log('\n🎉 所有关注与自动加好友相关功能测试通过！');
  } catch (e) {
    console.error('❌ 测试失败:', e.message, e.response?.data, e);
  }
  finally {
    await pool.end();
  }
}

main(); 